package org.eco.generator.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollectionUtil;
import org.eco.generator.service.IGenTableColumnService;
import org.eco.generator.service.IGenTableService;
import org.eco.common.core.core.domain.CommonResult;
import org.eco.common.core.core.page.PageResult;
import org.eco.common.core.core.text.Convert;
import org.eco.common.web.core.BaseController;
import org.eco.generator.domain.GenTable;
import org.eco.generator.domain.GenTableColumn;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 * @author wgk
 */
@Validated
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {
    @Resource
    private IGenTableService genTableService;

    @Resource
    private IGenTableColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */
    @SaCheckPermission("tool:gen:list")
    @GetMapping("/list")
    public CommonResult<PageResult<GenTable>> genList(GenTable genTable) {
        return CommonResult.success(genTableService.selectPage(genTable));
    }

    /**
     * 修改代码生成业务
     */
    @SaCheckPermission("tool:gen:query")
    @GetMapping(value = "/{tableId}")
    public CommonResult<Map<String, Object>> getInfo(@PathVariable Long tableId) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return CommonResult.success(map);
    }

    /**
     * 查询数据库列表
     */
    @SaCheckPermission("tool:gen:list")
    @GetMapping("/db/list")
    public CommonResult<PageResult<GenTable>> dataList(GenTable genTable) {
        PageResult<GenTable> list = genTableService.selectDbTableList(genTable);
        return CommonResult.success(list);
    }

    /**
     * 查询数据表字段列表
     */
    @SaCheckPermission("tool:gen:list")
    @GetMapping(value = "/column/{tableId}")
    public CommonResult<PageResult<GenTableColumn>> columnList(@PathVariable("tableId") Long tableId) {
        PageResult<GenTableColumn> list = genTableColumnService.selectPageGenTableColumnListByTableId(tableId);
        return CommonResult.success(list);
    }

    /**
     * 导入表结构（保存）
     */
    @SaCheckPermission("tool:gen:import")
    @PostMapping("/importTable")
    public CommonResult<Void> importTableSave(@RequestBody String[] tables) {
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tables);
        if(CollectionUtil.isEmpty(tableList)) {
            return CommonResult.fail("表源不存在");
        }
        genTableService.importGenTable(tableList);
        return CommonResult.success();
    }

    /**
     * 修改保存代码生成业务
     */
    @SaCheckPermission("tool:gen:edit")
    @PutMapping
    public CommonResult<Void> editSave(@Validated @RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return CommonResult.success();
    }

    /**
     * 删除代码生成
     */
    @SaCheckPermission("tool:gen:remove")
    @DeleteMapping("/{tableIds}")
    public CommonResult<Void> remove(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return CommonResult.success();
    }

    /**
     * 预览代码
     */
    @SaCheckPermission("tool:gen:preview")
    @GetMapping("/preview/{tableId}")
    public CommonResult<Map<String, String>> preview(@PathVariable("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return CommonResult.success(dataMap);
    }

    /**
     * 生成代码（自定义路径）
     */
    @SaCheckPermission("tool:gen:code")
    @GetMapping("/genCode")
    public CommonResult<Void> genCode(Long tableId) {
        genTableService.generatorCode(tableId);
        return CommonResult.success();
    }

    /**
     * 同步数据库
     */
    @SaCheckPermission("tool:gen:edit")
    @GetMapping("/syncDb/{tableId}")
    public CommonResult<Void> syncDb(@PathVariable("tableId") Long tableId) {
        genTableService.syncDb(tableId);
        return CommonResult.success();
    }

    /**
     * 批量生成代码
     */
    @SaCheckPermission("tool:gen:code")
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableIds = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableIds);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"eco-code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
